/**
 * Created by jiangxiaowei on 2017/4/25.
 */

import * as React from "react";
import { Relax } from "iflux2";
import { List } from "immutable";
import { Layout, Tabs, Spin } from "antd";
import Template from "./template";
import ExpireLock from "expire-lock";

declare let window: any;

const { Content } = Layout;
const TabPane = Tabs.TabPane;

const PLATFORM_INFO = {
  pc: "PC端",
  weixin: "微信端",
  app: "APP端"
};

@Relax
export default class TemplateManageMain extends React.Component<any, any> {
  constructor(props) {
    super(props);
    let tip = "加载中";
    if (window.isUpdating) {
      tip = "又有新惊喜啦！建站升级中，请稍等一会儿吧～";
    }
    this.state = {
      selectRow: 1,
      platform: "pc",
      loading: true,
      tip
    };
  }

  static defaultProps = {
    templateList: List(), //模板列表
    pageTypeTab: List(), //模板pageType筛选按钮
    platformTab: List(), //平台tab切换按钮
    totalCount: 0, //模板总数量
    getTemplateList: () => {}, //store层的获取模板列表函数
    getPlatformBtnList: () => {},
    getPageTypeBtnList: () => {},
    getPageTypeCount: () => {},
    getActivatedPageInfo: () => {}
  };

  componentDidMount() {
    //初始化数据
    let target = this;
    if (window.isUpdating) {
      let dom: any = document.getElementsByClassName("ant-spin-blur");
      if (dom.length > 0) {
        dom[0].style.opacity = 0;
      }
    } else {
      (async () => {
        await target.props.getPlatformBtnList();
        await target.props.getPageTypeBtnList({ platform: "pc" });
        await target.props.getPageTypeCount({
          platform: "pc",
          pageType: JSON.stringify("index")
        });
        target.props
          .getTemplateList({ platform: "pc", includePageTypeList: ["index"] })
          .then(
            () => {
              target.setState({ loading: false });
            },
            err => {
              console.log(err);
              target.setState({ loading: false });
            }
          );
        target.props.getActivatedPageInfo();
      })();
    }
  }

  render() {
    let searchBtns = this.props.pageTypeTab.map(item => {
      return (
        <div
          key={item.get("id").toString()}
          className={`template-page${this.state.selectRow === item.get("id")
            ? " active"
            : ""}`}
          onClick={this.handleClick.bind(this, item)}
        >
          <span className="page">
            <span>
              {item.get("name")}
            </span>
          </span>
        </div>
      );
    });

    let more_template = this.state.loading
      ? null
      : <div className="template">
          <img src="//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/images/more_template.png" />
        </div>;

    let templateList = this.props.templateList;
    let tabPanes = this.props.platformTab.map(item => {
      let tplList = templateList.get(item.get("type")).get("tplList");
      let templates =
        tplList &&
        tplList.map(tpl => {
          return (
            <Template
              key={tpl.toString()}
              templateInfo={tpl}
              platform={this.state.platform}
            />
          );
        });
      return (
        <TabPane tab={PLATFORM_INFO[item.get("type")]} key={item.get("type")}>
          <div
            className="template-type"
            style={{ width: "100%", marginTop: "-20px" }}
          >
            <span className="title">页面类型:</span>
            {searchBtns}
          </div>
          {templates}
          {more_template}
        </TabPane>
      );
    });
    return (
      <Spin spinning={this.state.loading} tip={this.state.tip}>
        <Layout>
          <Content>
            <div className="template-content">
              <Tabs defaultActiveKey="pc" onChange={this._changeTab.bind(this)}>
                {tabPanes}
              </Tabs>
            </div>
          </Content>
        </Layout>
      </Spin>
    );
  }

  @ExpireLock()
  handleClick(pageType) {
    if (this.state.selectRow !== pageType.get("id")) {
      this.setState({ selectRow: pageType.get("id") });
      this.props.getTemplateList({
        platform: this.state.platform,
        includePageTypeList: pageType.get("typeList")
      });
    } else {
      this.setState({ selectRow: "" });
      this.props.getTemplateList({ platform: this.state.platform });
    }
  }

  //切换tab页
  _changeTab(key) {
    let _target = this;
    _target.setState({ platform: key, selectRow: 1 }, () => {
      _target.props.getTemplateList({
        platform: key,
        includePageTypeList: ["index"]
      });
      _target.props.getPageTypeBtnList({ platform: key });
    });
  }
}
